<?php

use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
use \GatewayWorker\Lib\Store;
use \GatewayWorker\Lib\MongoDB;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 *
 * GatewayWorker开发参见手册：
 * @link http://gatewayworker-doc.workerman.net/
 */
class Event {
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     * @link http://gatewayworker-doc.workerman.net/gateway-worker-development/onconnect.html
     */
    public static function onConnect($client_id) {

        Gateway::sendToClient($client_id, "connection successful");

    }

    /**
     * 当客户端发来消息时触发
     * @param int    $client_id 连接id
     * @param string $message 具体消息
     * @link http://gatewayworker-doc.workerman.net/gateway-worker-development/onmessage.html
     */
    public static function onMessage($client_id, $message) {

        echo $message . "\n";

        $message = json_decode($message, 1);
        $type    = $message['type'];
        if (!$message || !$type) {

            return false;
        } else {

            $function = 'handle' . ucfirst($type);
            if (!method_exists(__CLASS__, $function)) {
                return false;
            }
            self::$function($client_id, $message);
        }

    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id) {

        $bind_key  = 'kf_bind_' . $client_id;
        $bind_data = Store::instance('kf')->get($bind_key);

        $identity  = $bind_data['identity'];
        $group_key = 'kf_group_' . $identity;

        Store::instance('kf')->del($bind_key);
        Store::instance('kf')->sRem($group_key, $client_id);

        switch ($identity) {

            case 'kf':

                $token_key = 'kf_kftoken_' . $bind_data['uid'];
                Store::instance('kf')->del($token_key);

                Gateway::sendToAll(json_encode([
                    'type'      => 'logout',
                    'identity'  => 'kf',
                    'uid'       => $bind_data['uid'],
                    'cliend_id' => $client_id,
                    'nickname'  => $bind_data['nickname'],
                ]));

                break;

            case 'anonymous':

                self::sendToAllkf(json_encode([
                    'type'      => 'logout',
                    'identity'  => 'anonymous',
                    'uid'       => $bind_data['uid'],
                    'cliend_id' => $client_id,
                    'nickname'  => $bind_data['nickname'],
                ]));
                break;

        }
    }

    /**
     * 发送给所有客服
     * @param $json
     * @throws Exception
     */
    public static function sendToAllkf($json) {

        $group_key  = 'kf_group_kf';
        $client_ids = Store::instance('kf')->sMembers($group_key);
        if (!empty($client_ids)) {

            foreach ($client_ids as $client_id) {

                Gateway::sendToClient($client_id, $json);
            }
        }
    }

    /**
     * 处理游客、客户登录
     * @param $client_id
     * @param $data
     * @throws Exception
     */
    public static function handleLogin($client_id, $data) {

        $token = $data['token'];
        if (!$token) {
            // 游客
            $bind_key  = 'kf_bind_' . $client_id;
            $bind_data = [
                'identity'  => 'anonymous',
                'uid'       => 0,
                'client_id' => $client_id,
                'nickname'  => '游客' . $client_id,
                'time'      => time()
            ];
            $group_key = 'kf_group_anonymous';

            Store::instance('kf')->set($bind_key, $bind_data);
            Store::instance('kf')->sAdd($group_key, $client_id);

            Gateway::sendToCurrentClient(json_encode([
                'type' => 'loginResult',
                'code' => 0,
                'msg'  => '欢迎您，' . $bind_data['nickname'],
            ]));
        }
    }

    /**
     * 处理客服登录
     * @param $client_id
     * @param $data
     * @throws Exception
     */
    public static function handleKflogin($client_id, $data) {

        $uid       = $data['uid'];
        $token     = $data['token'];
        $token_key = 'kf_kftoken_' . $uid;
        if (Store::instance('kf')->get($token_key) == $token) {

            $result = Db::instance('kf')->query("SELECT `nickname` FROM `kf` WHERE `id` = $uid");

            $bind_key  = 'kf_bind_' . $client_id;
            $bind_data = [
                'identity'  => 'kf',
                'uid'       => $uid,
                'client_id' => $client_id,
                'nickname'  => $result[0]['nickname'] ? $result[0]['nickname'] : '客服' . $uid,
                'time'      => time()
            ];
            $group_key = 'kf_group_kf';

            Store::instance('kf')->set($bind_key, $bind_data);
            Store::instance('kf')->sAdd($group_key, $client_id);
            Gateway::bindUid($client_id, $uid);

            echo $bind_data['nickname'] . '上线' . "\n";
            Gateway::sendToCurrentClient(json_encode([
                'type' => 'loginResult',
                'code' => 0,
                'msg'  => '欢迎您，' . $bind_data['nickname'],
            ]));
            Gateway::sendToAll(json_encode([
                'type'      => 'login',
                'identity'  => 'kf',
                'uid'       => $uid,
                'client_id' => $client_id,
                'nickname'  => $bind_data['nickname'],
            ]));

        } else {
            //echo "token_key: $token_key \n";
            //echo "get token:" . $token . "\n";
            //echo "set token:" . Store::instance('kf')->get($token_key) . "\n";
            echo "miss token \n";
            Gateway::sendToCurrentClient(json_encode([
                'type' => 'loginResult',
                'code' => -1,
                'msg'  => 'miss token',
            ]));
        }
    }

    /**
     * 获取客服列表
     */
    public static function handleKflist() {

        $group_key  = 'kf_group_kf';
        $client_ids = Store::instance('kf')->sMembers($group_key);
        $kflist     = array();
        if (!empty($client_ids)) {

            foreach ($client_ids as $client_id) {

                $bind_key = 'kf_bind_' . $client_id;
                $kflist[] = Store::instance('kf')->get($bind_key);

            }
        }

        Gateway::sendToCurrentClient(json_encode([
            'type' => 'kflist',
            'list' => $kflist
        ]));

    }

    /**
     * 发送消息
     * @param $client_id
     * @param $data
     */
    public static function handleSend($client_id, $data) {

        $sender_key  = 'kf_bind_' . $client_id;
        $sender_data = Store::instance('kf')->get($sender_key);

        $receiver_key  = 'kf_bind_' . $data['to'];
        $receiver_data = Store::instance('kf')->get($receiver_key);

        $message = [
            'type'    => 'message',
            'from'    => [
                $sender_data
            ],
            'message' => htmlspecialchars($data['message']),
        ];

        $save_data = [
            'form_uid'       => $sender_data['uid'],
            'form_client_id' => $sender_data['client_id'],
            'to_uid'         => $receiver_data['uid'],
            'to_client_id'   => $receiver_data['client_id'],
            'message'        => htmlspecialchars($data['message']),
        ];
        MongoDB::instance('kf')->kf->message->insert($save_data);

        if ($data['touid']) {
            Gateway::sendToUid($data['touid'], json_encode($message));
        } else {
            Gateway::sendToClient($data['to'], json_encode($message));
        }

    }

}
